package com.link.play.fit.ai.utils

import android.content.Context
import android.content.SharedPreferences
import java.util.*

object DailyFirstLaunchUtil {
    private const val PREFS_NAME = "daily_first_launch_prefs"
    private const val KEY_LAST_LAUNCH_TIME = "last_launch_time"

    /**
     * 检查是否为当天首次启动
     * @return true: 是当天首次进入, false: 非首次进入
     */
    fun isFirstLaunchToday(context: Context): Boolean {
        val prefs: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
        val lastLaunchTime = prefs.getLong(KEY_LAST_LAUNCH_TIME, 0)
        val todayStartTime = getTodayStartTime()

        if (lastLaunchTime < todayStartTime) {
            // 是当天首次，更新记录时间
            prefs.edit().putLong(KEY_LAST_LAUNCH_TIME, todayStartTime).apply()
            return true
        }
        return false
    }

    /**
     * 检查是否为当天首次锻炼打卡
     * @return true: 是当天首次点击，false: 非首次
     */
    fun isFirstExerciseToday(context: Context): Boolean {
        val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
        val key = "exerciseCal"
        val lastClickTime = prefs.getLong(key, 0)
        val todayStartTime = getTodayStartTime()

        if (lastClickTime < todayStartTime) {
            // 更新为当天零点时间，避免重复触发
            prefs.edit().putLong(key, todayStartTime).apply()
            return true
        }
        return false
    }

    /**
     * 获取当天 00:00:00 的时间戳（基于本地时区）
     */
    private fun getTodayStartTime(): Long {
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.HOUR_OF_DAY, 0)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        calendar.set(Calendar.MILLISECOND, 0)
        return calendar.timeInMillis
    }

    /**
     * 清除记录（用于测试或重置）
     */
    fun clearRecord(context: Context) {
        val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
        prefs.edit().remove(KEY_LAST_LAUNCH_TIME).apply()
    }
}
